package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    //创建的就是Socket 不是ServerSocket
    private Socket socket = null;
    public TcpEchoClient (String serverIp, int serverPort) throws IOException {
        //这里的构造过程就会和服务器之间建立tcp连接
        //具体建立连接的过程,是系统内核完成 的
        socket = new Socket(serverIp,serverPort);
    }

    public void start() {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scannerNetwork = new Scanner(inputStream);
            while (true) {
                //1.从控制台读取数据
                System.out.println("请输入你要发送的数据: ");
                String request = scanner.next();
                //2ba请求发送到服务器,发送请求要带有\n,和服务器的scanner.next是对应的
                //由于上诉通过next读到的request本身已经没有\n结尾  ,要手动添加换行
                request += "\n";
                outputStream.write(request.getBytes());
                outputStream.flush();  //刷新
                //从服务器读取到回应
                if (!scannerNetwork.hasNext()) {
                    break;
                }
                String response = scannerNetwork.next();
                //把想要显示在控制台上
                System.out.println(response);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }







    public static void main(String[] args) throws IOException {

        TcpEchoClient server = new TcpEchoClient("172.17.239.40",9090);
        server.start();
    }
}
